import { NextApiRequest, NextApiResponse } from "next";
import { SolrResponse } from "~/types/solr";

const SOLR_HOST = process.env.SOLR_HOST as string

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  const productId = req.query.id as string
  const category = req.query.category as string

  if (req.method === 'GET') {
    const queryParams = new URLSearchParams({ q: `product_ids:${productId}` })
    queryParams.append('fq', `type_value_s:${category}`)
    queryParams.append('fq', `active_b:true`)

    const response = await fetch(`${SOLR_HOST}/solr/promotion_program_lines/select?${queryParams.toString()}`)
    const data: SolrResponse<any[]> = await response.json()

    const promotions = await map(data.response.docs)
    res.status(200).json({ data: promotions })
  }
}

const map = async (promotions: any[]) => {
  const result = []

  for (const promotion of promotions) {
    const data: any = {}

    data.id = promotion.id
    data.program_id = promotion.program_id_i
    data.name = promotion.name_s
    data.type = {
      value: promotion.type_value_s,
      label: promotion.type_label_s,
    }
    data.limit = promotion.package_limit_i
    data.limit_user = promotion.package_limit_user_i
    data.limit_trx = promotion.package_limit_trx_i
    data.price = promotion.price_f
    data.total_qty = promotion.total_qty_i

    data.products = JSON.parse(promotion.products_s)
    data.free_products = JSON.parse(promotion.free_products_s)

    result.push(data)
  }

  return result
}